package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmUser;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;

/**
 * @author 嘉德罗斯
 * @date 2021/11/19
 */
@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ApArticleMapper,ApArticle> implements ArticleService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;


    @Override
    public List<ApArticle> load(ArticleHomeDto dto) {
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getChannelId,dto.getTag());
        int i = 0;
        if ("__all__".equals(dto.getTag())){
            queryWrapper = new LambdaQueryWrapper<>();
        }
        if ("__dyna__".equals(dto.getTag())){
            queryWrapper = new LambdaQueryWrapper<>();
            List<ApArticle> apArticles = apArticleMapper.selectList(null);
            Random r = new Random();
            i = r.nextInt(apArticles.size())-10;
        }
        queryWrapper.orderByDesc(ApArticle::getPublishTime);
        queryWrapper.lt(ApArticle::getPublishTime,dto.getMinBehotTime());
        Page<ApArticle> page = new Page(i,dto.getSize());
        IPage<ApArticle> apArticlePage = apArticleMapper.selectPage(page, queryWrapper);
        List<ApArticle> records = apArticlePage.getRecords();

        List<Long> list = new ArrayList<>();
        for (ApArticle record : records) {
            list.add(record.getId());
        }
        LambdaQueryWrapper<ApArticleConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(ApArticleConfig::getArticleId,list);
        List<ApArticleConfig> apArticleConfigs = apArticleConfigMapper.selectList(lambdaQueryWrapper);

        Map<Long,ApArticleConfig> map = new HashMap();
        for (ApArticleConfig apArticleConfig : apArticleConfigs) {
            map.put(apArticleConfig.getArticleId(),apArticleConfig);
        }

        List <Integer> arr = new ArrayList<>();
        for (int a = 0;a<records.size(); a++) {
            if (map.get(records.get(a).getId()).getIsDown()||map.get(records.get(i).getId()).getIsDelete()) {
                arr.add(a);
                continue;
            }
        }

        for (int a: arr) {
            ApArticle remove = records.remove(a);
            System.out.println(remove);
        }
        return records;
    }

    @Override
    public Long saveArticle(ApArticleDto dto) {
        //上传文件获取url
        String url = upload(dto);
        ApArticle apArticle = new ApArticle(dto);
        apArticle.setStaticUrl(url);
        apArticleMapper.insert(apArticle);
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(dto.getContent());
        apArticleContentMapper.insert(apArticleContent);
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfigMapper.insert(apArticleConfig);
        return apArticle.getId();
    }

    @Override
    public String getUrl(Long articleId) {
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        return apArticle.getStaticUrl();
    }

    @Override
    public ResponseResult delete(Long articleId) {
        apArticleMapper.deleteById(articleId);
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId,articleId);
        apArticleContentMapper.delete(queryWrapper);
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsDelete(true);
        apArticleConfig.setArticleId(articleId);
        LambdaQueryWrapper<ApArticleConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(ApArticleConfig::getArticleId,apArticleConfig);
        apArticleConfigMapper.update(apArticleConfig,configLambdaQueryWrapper);
        return ResponseResult.okResult("成功");
    }

    private String upload(ApArticleDto dto) {
        //2.文章内容通过freemarker生成html文件
        StringWriter out = null;
        try {
            out = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");
            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(dto.getContent()));
            template.process(params, out);
        } catch (IOException e) {

        } catch (TemplateException e) {
            e.printStackTrace();
        }
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        //3.把html文件上传到minio中
        String uuid = UUID.randomUUID().toString();
        String path = fileStorageService.uploadHtmlFile("", uuid + ".html", is);
        return path;
    }
}

